// pages/category/category.js
const app = getApp();
Page({
  data: {
    categories: [],
    currentCategory: 0,
    options: false,
    curOption: -1
  },
  onLoad(options) {
    this.callbackPath = options.callback;
    this.loadData();
  },
  loadData() {
    const that = this;
    app.request('/api/question/category').then(res => {
      // 剥离vip字段
      let categories = res.data.data;
      let vips = [];
      for (const item of categories) {
        vips.push(item.vip);
        delete item.vip;
      }
      that.vips = vips;
      that.setData({
        categories: categories,
        options: categories[0].childlist
      });
    }).catch(err => {
      console.error(err);
    });
  },

  selectCategory(e) {
    console.log(e);
    this.setData({
      currentCategory: e.currentTarget.dataset.index,
      options: this.data.categories[e.currentTarget.dataset.index].childlist
    });
  },
  selectOption(e) {
    wx.setStorage({
      key: 'category',
      data: this.data.options[e.target.dataset.index]
    });
    app.globalData.category = this.data.options[e.target.dataset.index];
    app.globalData.exam1ParamsNeedLoad = true;
    app.globalData.exam1Params = {};
    // 一定要存在vip字段，不存在就再获取一遍
    const that = this;
    if (!app.globalData.userinfo) {
      wx.switchTab({
        url: that.callbackPath
      });
    } else {
      app.request('/api/user/info', {question_category_id: this.data.options[e.target.dataset.index].id}).then(res => {
        if (res.data.code === 1) {
          app.globalData.userinfo = res.data.data;
        }
        wx.switchTab({
          url: that.callbackPath
        });
      }).catch(err => {
        console.error(err);
      });
    }
  }
});